var $table = $("#managerOrderTab");
var manifestId;	//货单id
var manifestNum;	//货单编号
var initOrders;	//刚加载的时候获取已选中的行
var stationArea;
$(function () {
	manifestId = $.getUrlParam("id");
	manifestNum = $.getUrlParam("num");
	
	//通过货单id查询货单的信息，在页面上方展示
	$.ajax({
        url: "../manifest/getManifestInfoById.htm",
        cache: false,
        type: "post",
        dataType: "json",
        data: {'manifestId': manifestId},
        success: function (result) {
            if (result.status == 0) {
            	var data = result.data;
            	$("#manifestInfoForm").formatForm(data);
            	//通过城市查询区域名，放入下拉列表中
            	$.ajax({
                    url: "../manifest/getAreaByCity.htm",
                    cache: false,
                    type: "post",
                    dataType: "json",
                    async:false,	//同步
                    data: {'city': data.stationCity},
                    success: function (result) {
                        if (result.status == 0) {
                        	var data = result.data;
                        	addOptions(data, "#stationArea");
                        	//获取被选中的区域
                        	stationArea = $('#stationArea').find("option:selected").text();
                        	//初始化订单表格
                        	initTable();
                        } else {
                            layer.msg(result.message, {icon: 2});
                        }
                    }
                });
            	
            } else {
                layer.msg(result.message, {icon: 2});
            }
        }
    });
	
    
    //查询事件
    $("#queryOrderBtn").click(function () {
    	//获取区域里的text值
        var stationArea = $('#stationArea').find("option:selected").text();
        //使用post提交
        $table.bootstrapTable('refresh', {
            silent: false,
            url: '../manifest/getOrderFromManifest.htm',	//../order/getAllPayFailOrderPage.htm
            query:{stationArea:stationArea, manifestNum: manifestNum}
        });
    });
    
    //批量增加订单按钮
    $("#batchAddBut").click(function(){
    	//点击按钮获取选中的行，当没有选择任何一行时返回一个空数组
    	var afterOrders = $table.bootstrapTable("getSelections");
    	if(afterOrders.length == 0){
    		layer.msg("请最少选择一行", {icon: 2});
    	}else{
    		var initOrderNums = [];	//初始化获取被选中的订单编号
    		for (var i = 0; i < initOrders.length; i++) {
    			initOrderNums.push(initOrders[i].orderNum);
			}
    		var afterOrderNums = []; //点击批量增加时获取被选中的订单编号
    		for (var i = 0; i < afterOrders.length; i++) {
    			afterOrderNums.push(afterOrders[i].orderNum);
    		}
    		//比较是否有变化
    		var flag = JSON.stringify(initOrderNums) == JSON.stringify(afterOrderNums);
    		if(flag){
    			layer.msg("订单无变化，无需保存，直接关闭!", {icon: 2});
    			return;
    		}else{
    			//下面判断加载时和点击保存时，选择的行数据的变化，把已经存在的去掉
    			var temp = [];
    			var temparray = [];
    			for (var i = 0; i < initOrders.length; i++) { 
					temp[initOrders[i].orderNum] = true; 
				};
				for (var i = 0; i < afterOrders.length; i++) { 
					if (!temp[afterOrders[i].orderNum]) { 
						temparray.push(afterOrders[i].orderNum); 
					}; 
				};
        		layer.confirm('你确定将订单号【' + temparray + '】加入货单吗？', {
        	        btn: ['确定', '取消'] //按钮
        	    }, function () {
        	        $.ajax({
        	            url: "../manifest/batchOrderAddToManifest.htm",
        	            cache: false,
        	            traditional: true,
        	            type: "post",
        	            dataType: "json",
        	            data: {'orderNums': temparray, "manifestNum":manifestNum},
        	            success: function (result) {
        	                if (result.status == 0) {
        	                    layer.msg(result.message, {icon: 1});
        	                    $table.bootstrapTable('refresh', {url: '../manifest/getOrderFromManifest.htm'});
        	                    return;
        	                }
        	                layer.msg(result.message, {icon: 2});
        	            }
        	        });
        	    }, function () {}
        		);
    		}
    	}
    });
   
});

//table 不使用分页
function initTable() {
    $table.bootstrapTable({
        dataType: "json",
        showColumns: true, 
//        pagination: false, //分页
        striped: true,
        cache: false,	//是否使用缓存，默认是true
//        pageSize: 10,
//        pageNumber: 1,
//        queryParamsType: 'limit',
//        smartDisplay: true,
//        sidePagination: "server",
        method: "post",	//使用post提交
        url: '../manifest/getOrderFromManifest.htm',
        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
        queryParams: {stationArea:stationArea, manifestNum: manifestNum},	//初始化的时候就要传一个货单号和区域名
        rowStyle: function(row, index){
        	var strClass = "";
        	if(row.orderIsManifest == 1){ //改变已经被添加到货单里的订单改变行样式
        		strClass = "success";
			}else{
				return {};
			}
        	return {classes: strClass};
        },
        columns: [
        	{
        		align: "center",
        		checkbox: true,
        		formatter: function(value, row, index){
        			if(row.orderIsManifest == 1){
        				return {
        					disabled:true,	//设置是否可用
        					checked: true	//设置选中
        				};
        			}
        		}
        	},
            {
                title: "序号",
                align: 'center',
                formatter:function(value,row,index){
                    return index + 1;
                }
            },
            {
                title: "订单号",
                field: "orderNum",
                align: 'center',
                valign: 'middle'
            },
            {
                title: "寄件人姓名",
                field: "sender.senderName",
                align: 'center', 
                valign: 'middle',
                valign: 'middle'
            },
            {
                title: "寄件人电话",
                field: "sender.senderPhone",
                align: 'center',
                valign: 'middle'
            },
            {
                title: "寄件人地址",
                field: "sender.senderAddr",
                align: 'center',
                valign: 'middle'
            },
            {
                title: "收件人姓名",
                field: "reciver.reciverName",
                align: 'center',
                valign: 'middle',
                valign: 'middle'
            },
            {
                title: "收件人电话",
                field: "reciver.reciverPhone",
                align: 'center',
                valign: 'middle'
            },
            {
                title: "收件人地址",
                field: "reciver.reciverAddr",
                align: 'center',
                valign: 'middle'
            },
            {
                title: "货物名称",
                field: "cargo.cargoName",
                align: 'center',
                valign: 'middle',
                valign: 'middle'
            },
            {
                title: "件数",
                field: "cargo.cargoAmount",
                align: 'center',
                valign: 'middle'
            },
            {
                title: "仓库名",
                align: 'center',
                formatter: function(value, row, index){
                	if(typeof(row.storage) == 'undefined'){
                		return '-';
                	}else{
                		return row.storage.storageName;
                	}
                }
            },
            {
                title: "支付状态",
                field: "orderManifestState",
                align: 'center',
                formatter: function(value, row, index){
                    var oms = "-";
                    if(row.orderManifestState == 0){
                    	oms = '<span style="color:#ed5565;">未支付</span>';
                    }else if(row.orderManifestState == 1){
                    	oms ='<span style="color:#23c6c8;">已支付</span>';
                    }else if(row.orderManifestState == 3){
                    	oms ='<span style="color:#f8ac59;">支付异常</span>';
                    }
                    return oms;
                }
            },
            {
            	title: "代收货款金额",
                field: "orderCod",
                align: 'center',
                valign: 'middle'
            },
            {
            	title: "是否货到付款",
                field: "orderFreightForward",
                align: 'center',
                formatter: function(value, row, index){
                    var orderFF = "-";
                    if(row.orderFreightForward > 0.00){
                    	orderFF = '<span style="color:#ed5565;">是</span>';
                    }else if(row.orderManifestState == 0.00){
                    	orderFF ='<span style="color:#23c6c8;">否</span>';
                    }
                    return orderFF;
                }
            },
            {
                title: "操作",
                align: 'center',
                formatter: function (value, row, index) {
                    var d = '';
                    if(row.orderIsManifest == 1){
                    	d = '<button class="btn btn-sm btn-danger" type="button" onclick="removeOrder(\'' + row.orderId + '\',\'' + row.orderNum + '\')"><i class="fa fa-trash-o"></i>移除货单</button> ';
                    }
                    return d;
                }
            }
        ],
        onLoadSuccess: function(data){
        	//表格加载完成后获取被选中的行
            initOrders = $table.bootstrapTable("getSelections");
        }
    });
}

//从 货单中移除订单
function removeOrder(id, orderNum) {
    layer.confirm('确定要移除编号【'+ orderNum +'】的订单吗？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        $.ajax({
            url: "../manifest/removeOrderFromManifest.htm",
            cache: false,
            type: "post",
            dataType: "json",
            data: {'orderNum': orderNum},
            success: function (result) {
                if (result.status == 0) {
                    layer.msg(result.message, {icon: 1});
                    $table.bootstrapTable('refresh', {url: '../manifest/getOrderFromManifest.htm'});
                    return;
                }else{
                	layer.msg(result.message, {icon: 2});
                }
            }
        });
    }, function () {});
}


//table额外传参数
function queryParams(queryParamsType){
	var temp = {
//		limit: queryParamsType.limit,   //页面大小
//		offset: queryParamsType.offset,  //页码
		stationArea:stationArea,
		manifestNum: manifestNum
	}
	return temp;
}

//关闭窗口
function closeForm() {
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    parent.layer.close(index);
}

//区域下拉列表  追加到option中
function addOptions(data,selectId){
	for(var i=0;i<data.length;i++){
		$(selectId).append('<option value="">' + data[i] + '</option>');
	}
}
